﻿#include "radiobutton.h"
#include <QToolButton>
#include <QBoxLayout>
#include <QSignalMapper>
#include <QStyleOption>
#include <QPainter>

RadioButton::RadioButton(QWidget *parent)
    : QWidget(parent)
    , m_currentSelectedBtnIndex(0)
    , m_orientation(Qt::Horizontal)
    , m_spacing(0)
    , m_layout(nullptr)
{
    // 初始化布局
    if (m_orientation == Qt::Horizontal) {
        m_layout = new QHBoxLayout(this);
    } else {
        m_layout = new QVBoxLayout(this);
    }
    m_layout->setSpacing(m_spacing);
    m_layout->setContentsMargins(0, 0, 0, 0);
    setLayout(m_layout);
}

void RadioButton::setOrientation(Qt::Orientation orientation)
{
    if (m_orientation == orientation)
        return;

    // 保存当前按钮
    QVector<QToolButton*> buttons = m_selectedBtnList;
//    int currentIndex = m_currentSelectedBtnIndex;

    // 清空当前布局
    QLayoutItem *item;
    while ((item = m_layout->takeAt(0)) != nullptr) {
        if (item->widget())
            item->widget()->setParent(nullptr);
        delete item;
    }
    delete m_layout;

    // 创建新布局
    if (orientation == Qt::Horizontal) {
        m_layout = new QHBoxLayout(this);
        m_layout->setAlignment(Qt::AlignHCenter); // 居中
    } else {
        m_layout = new QVBoxLayout(this);
        m_layout->setAlignment(Qt::AlignHCenter); // 居中
    }
    m_layout->setSpacing(m_spacing);
    m_layout->setContentsMargins(0, 0, 0, 0);
    setLayout(m_layout);

    m_orientation = orientation;

    // 重新添加按钮
    for (QToolButton *btn : buttons) {
        m_layout->addWidget(btn);
    }

    updateButtonStyles();
    emit orientationChanged(m_orientation);

    setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
}

Qt::Orientation RadioButton::orientation() const
{
    return m_orientation;
}

void RadioButton::setSpacing(int spacing)
{
    if (m_spacing == spacing)
        return;

    m_spacing = spacing;
    m_layout->setSpacing(m_spacing);
    emit spacingChanged(m_spacing);
}

int RadioButton::spacing() const
{
    return m_spacing;
}

void RadioButton::addButton(const QString &text)
{
    QToolButton *button = new QToolButton(this);
    button->setText(text);
    button->setCheckable(true);
    button->setChecked(false);

    setupButton(button);

    m_selectedBtnList.append(button);
    m_layout->addWidget(button);

    // 如果是第一个按钮，设为选中
    if (m_selectedBtnList.size() == 1) {
        m_currentSelectedBtnIndex = 0;
        button->setChecked(true);
    }

    updateButtonStyles();
}

void RadioButton::addButtons(const QStringList &texts)
{
    for (const QString &text : texts) {
        addButton(text);
    }
}

int RadioButton::currentIndex() const
{
    return m_currentSelectedBtnIndex;
}

void RadioButton::setCurrentIndex(int index)
{
    if (index < 0 || index >= m_selectedBtnList.size() || index == m_currentSelectedBtnIndex)
        return;

    // 取消当前选中
    if (m_currentSelectedBtnIndex < m_selectedBtnList.size()) {
        m_selectedBtnList[m_currentSelectedBtnIndex]->setChecked(false);
    }

    m_currentSelectedBtnIndex = index;
    m_selectedBtnList[m_currentSelectedBtnIndex]->setChecked(true);

    updateButtonStyles();
    emit currentIndexChanged(m_currentSelectedBtnIndex);
}

int RadioButton::count() const
{
    return m_selectedBtnList.size();
}

void RadioButton::setupButton(QToolButton *button)
{
    button->setAutoExclusive(false); // 由我们手动控制互斥
    connect(button, &QToolButton::clicked, this, &RadioButton::onButtonClicked);

    // 设置样式表基础
    button->setStyleSheet(R"(
        QToolButton {
            background: #FFFFFF;
            border: 1px solid #CCCCCC;
            padding: 8px 12px;
            font: 12px;
        }
        QToolButton:hover {
            border-color: #6FD9FF;
        }
        QToolButton:checked {
            border-color: #6FD9FF;
            color: #6FD9FF;
        }
    )");
}

void RadioButton::onButtonClicked()
{
    QToolButton *btn = qobject_cast<QToolButton*>(sender());
    if (!btn) return;

    int index = m_selectedBtnList.indexOf(btn);
    if (index == -1 || index == (int)m_currentSelectedBtnIndex)
        return;

    m_currentSelectedBtnIndex = index;

    // 手动更新选中状态
    for (int i = 0; i < m_selectedBtnList.size(); ++i) {
        m_selectedBtnList[i]->setChecked(i == (int)m_currentSelectedBtnIndex);
    }

    updateButtonStyles();
    emit currentIndexChanged(m_currentSelectedBtnIndex);
    emit buttonClicked(m_currentSelectedBtnIndex);
}

void RadioButton::updateButtonStyles()
{
    int count = m_selectedBtnList.size();
    if (count == 0) return;

    for (int i = 0; i < count; ++i) {
        QToolButton *btn = m_selectedBtnList[i];
        bool isChecked = (i == (int)m_currentSelectedBtnIndex);
        QString extraStyle;

        if (m_orientation == Qt::Horizontal) {
            if (i == 0) {
                // 最左侧按钮：左上、左下圆角
                extraStyle = "border-top-left-radius: 4px; border-bottom-left-radius: 4px;";
            } else if (i == count - 1) {
                // 最右侧按钮：右上、右下圆角
                extraStyle = "border-top-right-radius: 4px; border-bottom-right-radius: 4px;";
            } else {
                extraStyle = "border-radius: 0;";
            }
        } else { // Vertical
            if (i == 0) {
                // 最上方按钮：左上、右上圆角
                extraStyle = "border-top-left-radius: 4px; border-top-right-radius: 4px;";
            } else if (i == count - 1) {
                // 最下方按钮：左下、右下圆角
                extraStyle = "border-bottom-left-radius: 4px; border-bottom-right-radius: 4px;";
            } else {
                extraStyle = "border-radius: 0;";
            }
        }

        // 选中时边框颜色为 #6FD9FF
        if (isChecked) {
            extraStyle += " border-color: #6FD9FF;";
        }

        btn->setStyleSheet(QString(R"(
            QToolButton {
                background: #FFFFFF;
                border: 1px solid #CCCCCC;
                padding: 8px 12px;
                font: 12px;
                %1
            }
            QToolButton:hover {
                border-color: #6FD9FF;
            }
            QToolButton:checked {
                border-color: #6FD9FF;
                color: #6FD9FF;
            }
        )").arg(extraStyle));
    }
}

void RadioButton::paintEvent(QPaintEvent *event)
{
    QStyleOption opt;
    opt.initFrom(this);
    QPainter p(this);
    style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this);

    QWidget::paintEvent(event);
}
